package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //处理查询所有部门的请求
    @RequestMapping("/list")
    public String list(Model model,QueryObject qo){
        //查询所有部门数据,存在模型
        //List<Role> roles = roleService.listAll();
        //处理分页查询部门的请求
        //model.addAttribute("roles",roles);
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageResult",pageInfo);
        return "role/list";  //  /WEB-INF/views/role/list.ftl
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                roleService.delete(id);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    //处理去新增请求
    @RequestMapping("/input")
    //@RequirePermission(name = "角色新增",expression = "role:input")
    public String input(Long id,Model model){
        model.addAttribute("permissions",permissionService.listAll());

        //如果传id就传去修改
        if (id!=null){
            model.addAttribute("role",roleService.get(id));
        }
        return "role/input";
    }

    //处理新增请求
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        if (role.getId()!=null){
            //修改
            roleService.update(role,ids);
        }else {
            //新增
            roleService.save(role,ids);
        }
        return "redirect:/role/list.do";
    }


}
